import axios from 'axios'

// 创建axios实例
const apiClient = axios.create({
  baseURL: 'http://localhost:5001',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
apiClient.interceptors.request.use(
  config => {
    // 这里可以添加token等认证信息
    // 暂时使用固定的dummy_token进行开发测试
    // 实际环境中应该从localStorage获取真实token
    const token = localStorage.getItem('token') || 'dummy_token'
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
apiClient.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    console.error('API请求错误:', error)
    // 可以在这里处理统一的错误逻辑
    if (error.response && error.response.status === 401) {
      // 未授权，可以跳转到登录页面
      console.log('需要重新登录')
    }
    return Promise.reject(error)
  }
)

// API接口封装
export const api = {
  // 系统相关
  system: {
    healthCheck: () => apiClient.get('/api/health'),
    getSystemInfo: () => apiClient.get('/api/system/info'),
    getStatistics: (params) => apiClient.get('/api/system/statistics', { params }),
    getResources: () => apiClient.get('/api/system/resources'),
    getLogs: (params) => apiClient.get('/api/system/logs', { params })
  },
  
  // 摄像头相关
  cameras: {
    getAllCameras: () => apiClient.get('/api/cameras'),
    getCameraDetail: (cameraId) => apiClient.get(`/api/cameras/${cameraId}`),
    addCamera: (cameraData) => apiClient.post('/api/cameras', cameraData),
    updateCamera: (cameraId, cameraData) => apiClient.put(`/api/cameras/${cameraId}`, cameraData),
    deleteCamera: (cameraId) => apiClient.delete(`/api/cameras/${cameraId}`),
    startCamera: (cameraId) => apiClient.post(`/api/cameras/${cameraId}/start`),
    stopCamera: (cameraId) => apiClient.post(`/api/cameras/${cameraId}/stop`),
    getCameraSnapshot: (cameraId) => apiClient.get(`/api/cameras/${cameraId}/snapshot`)
  },
  
  // 告警相关
  alerts: {
    getAlerts: (params) => apiClient.get('/api/alerts', { params }),
    getAlertDetail: (alertId) => apiClient.get(`/api/alerts/${alertId}`),
    confirmAlert: (alertId, data) => apiClient.post(`/api/alerts/${alertId}/acknowledge`, data),
    resolveAlert: (alertId, data) => apiClient.post(`/api/alerts/${alertId}/resolve`, data),
    getAlertImage: (alertId) => apiClient.get(`/api/alerts/${alertId}/image`),
    batchConfirmAlerts: (data) => apiClient.post('/api/alerts/batch/confirm', data)
  },
  
  // 文件检测相关（需要后端实现）
  detection: {
    detectImage: (formData) => apiClient.post('/api/detection/image', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }),
    detectVideo: (formData) => apiClient.post('/api/detection/video', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  }
}

export default api